package com.servlet;

import com.dao.implement.UserDaoImpl;
import com.model.User;
import com.utils.Md5Util;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Wray
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        /**
         * 编码
         */
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");


        PrintWriter out=response.getWriter();


        /**
         * 接受表单信息
         */
        String username = request.getParameter("username");
        String password = Md5Util.getmd5Str(request.getParameter("password"));
        String verifyc  = request.getParameter("verifycode");
        /**
         * 设置回显
         */

        //获取验证码
        String svc =(String) request.getSession().getAttribute("sessionverify");
        if(!svc.equalsIgnoreCase(verifyc)){
            request.setAttribute("username", username);
            request.setAttribute("loginError", "* 验证码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }
        User user=new UserDaoImpl().selectByUsername(username);
        if(user!=null){
            if(user.getPassword().equals(password)){
                request.setAttribute("username", username);
                request.setAttribute("password", password);
                request.setAttribute("verifycode", verifyc);
                request.getSession().setAttribute("user", user);
                request.getSession().setAttribute("message","登陆成功");
                response.sendRedirect("index.jsp");
            }else {
                request.setAttribute("username", username);
                request.setAttribute("loginError", "用户名或密码错误");
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
        }else{
            request.setAttribute("username", username);
            request.setAttribute("loginError", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
